package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.dto.AddressBookDto;
import com.sky.dto.IdDto;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.IAddressBookService;
import com.sky.vo.AddressBookVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
@Slf4j
public class AddressBookController {
    @Autowired
    private IAddressBookService addressBookService;

    /**
     * `新增地址
     *
     * @param addressBookDto
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody AddressBookDto addressBookDto) {
        // log.info("{}",addressBookDto.toString()+addressBookDto.getCityCode()); 测试成功
        addressBookDto.setUserId(BaseContext.getCurrentId());
        addressBookService.save(addressBookDto);
        return Result.success("新增地址成功");
    }

    /**
     * 根据用户id查询所有地址，并设置默认地址
     *
     * @return
     */
    @GetMapping("/list")
    public Result<List<AddressBookVo>> list() {
        Long userId = BaseContext.getCurrentId();
        List<AddressBookVo> bookVoList = addressBookService.list(userId);
        return Result.success(bookVoList);
    }

    /**
     * 查询默认地址
     *
     * @return
     */
    @GetMapping("/default")
    public Result<AddressBook> getByDefault() {
        AddressBook addressBook = addressBookService.getDefault();
        return Result.success(addressBook);
    }

    /**
     * 设置默认地址
     *
     * @param idDto
     * @return
     */
    @PutMapping("/default")
    public Result<String> modifyDefault(@RequestBody IdDto idDto) {
        log.info("{}", idDto);
        addressBookService.modifyDefault(idDto.getId());
        return Result.success("修改默认状态成功");
    }

    /**
     * @param id : 地址主键id
     * @return : 返回实体
     */
    @GetMapping("/{id}")
    public Result<AddressBook> getById(@PathVariable("id") Long id) {
        AddressBook addressBook = addressBookService.getById(id);
        return Result.success(addressBook);
    }

    /**
     * 根据id 删除地址
     *
     * @param id :
     * @return :
     */
    @DeleteMapping
    public Result<String> delete(Long id) {
        //log.info("{}",id); 测试成功
        addressBookService.deleteById(id);
        return Result.success("删除成功");
    }

    /**
     * 增加了注释
     *
     * @param addressBookDto
     * @return
     */
    @PutMapping
    public Result<String> modifyById(@RequestBody AddressBookDto addressBookDto) {
        // log.info("{}",addressBookDto.getId());测试成功
        addressBookService.modifyById(addressBookDto);
        return Result.success("修改地址成功");
    }
}
